<template>
  <div class="wallet-container">
    <h2 class="page-title">代币充值及提现</h2>
    
    <!-- 代币余额卡片 -->
    <el-card class="balance-card">
      <div class="balance-header">
        <h3>我的代币余额</h3>
        <el-tag type="success" size="large">{{ tokenBalance }} 代币</el-tag>
      </div>
      <div class="balance-actions">
        <el-button type="primary" @click="depositDialogVisible = true">充值</el-button>
        <el-button type="warning" @click="handleWithdraw">提现</el-button>
      </div>
    </el-card>
    
    <!-- 交易记录 -->
    <el-card class="transaction-card">
      <template #header>
        <div class="card-header">
          <span>交易记录</span>
          <el-radio-group v-model="transactionType" size="small" @change="loadTransactions">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="deposit">充值</el-radio-button>
            <el-radio-button label="withdraw">提现</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="transactions"
        style="width: 100%"
        :empty-text="loading ? '正在加载...' : '暂无交易记录'"
      >
        <el-table-column prop="id" label="交易ID" width="180" />
        <el-table-column label="类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'deposit' ? 'success' : 'warning'">
              {{ scope.row.type === 'deposit' ? '充值' : '提现' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="scope">
            {{ scope.row.amount }} 代币
          </template>
        </el-table-column>
        <el-table-column prop="date" label="时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.date) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)" 
              :effect="scope.row.status === 'processing' ? 'plain' : 'dark'"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" link @click="viewTransaction(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 充值对话框 -->
    <el-dialog
      v-model="depositDialogVisible"
      title="代币充值"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="depositFormRef" :model="depositForm" :rules="depositRules" label-width="100px">
        <el-form-item label="充值金额" prop="amount">
          <el-input-number
            v-model="depositForm.amount"
            :min="1"
            :precision="0"
            style="width: 100%"
            placeholder="请输入充值金额"
          />
        </el-form-item>
        <el-alert
          type="info"
          show-icon
          :closable="false"
          title="充值说明"
          description="充值后代币将立即添加到您的账户中，支持信用卡、支付宝等多种支付方式。"
        />
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="depositDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDeposit" :loading="depositLoading">
            确认充值
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 提现对话框 -->
    <el-dialog
      v-model="withdrawDialogVisible"
      title="代币提现"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="withdrawFormRef" :model="withdrawForm" :rules="withdrawRules" label-width="100px">
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="1"
            :max="tokenBalance"
            :precision="0"
            style="width: 100%"
            placeholder="请输入提现金额"
          />
        </el-form-item>
        <el-alert
          type="info"
          show-icon
          :closable="false"
          title="提现说明"
          description="提现申请提交后，代币将立即从您的账户中扣除，资金将在1-3个工作日内自动转入您的银行账户。"
        />
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="withdrawDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmWithdraw" :loading="withdrawLoading">
            确认提现
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 交易详情对话框 -->
    <el-dialog
      v-model="transactionDetailVisible"
      title="交易详情"
      width="30%"
    >
      <div v-if="selectedTransaction" class="transaction-detail">
        <div class="detail-item">
          <span class="label">交易ID:</span>
          <span class="value">{{ selectedTransaction.id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">类型:</span>
          <span class="value">
            {{ selectedTransaction.type === 'deposit' ? '充值' : '提现' }}
          </span>
        </div>
        <div class="detail-item">
          <span class="label">金额:</span>
          <span class="value">{{ selectedTransaction.amount }} 代币</span>
        </div>
        <div class="detail-item">
          <span class="label">时间:</span>
          <span class="value">{{ formatDate(selectedTransaction.date) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态:</span>
          <span class="value">
            <el-tag :type="getStatusType(selectedTransaction.status)">
              {{ getStatusText(selectedTransaction.status) }}
            </el-tag>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getTokenBalance, depositTokens, withdrawTokens, getTransactionHistory } from '@/api/wallet'

// 用户状态管理
const userStore = useUserStore()

// 判断用户类型
const isCompany = computed(() => userStore.isCompany)

// 余额相关
const tokenBalance = computed(() => userStore.tokenBalance)

// 交易记录相关
const loading = ref(false)
const transactions = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const transactionType = ref('')

// 充值相关
const depositDialogVisible = ref(false)
const depositLoading = ref(false)
const depositForm = reactive({
  amount: 100
})
const depositRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 1, message: '充值金额必须大于0', trigger: 'blur' }
  ]
}
const depositFormRef = ref(null)

// 提现相关
const withdrawDialogVisible = ref(false)
const withdrawLoading = ref(false)
const withdrawForm = reactive({
  amount: 0
})
const withdrawRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', min: 1, message: '提现金额必须大于0', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value > tokenBalance.value) {
          callback(new Error('提现金额不能大于余额'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const withdrawFormRef = ref(null)

// 交易详情相关
const transactionDetailVisible = ref(false)
const selectedTransaction = ref(null)

// 初始化数据
onMounted(() => {
  loadTokenBalance()
  loadTransactions()
})

// 加载代币余额
const loadTokenBalance = async () => {
  try {
    const response = await getTokenBalance()
    if (response.code === 200) {
      userStore.setUserInfo({
        ...userStore.userInfo,
        tokenBalance: response.data.balance
      })
    }
  } catch (error) {
    console.error('加载代币余额失败:', error)
  }
}

// 加载交易记录
const loadTransactions = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      type: transactionType.value
    }
    
    const response = await getTransactionHistory(params)
    if (response.code === 200) {
      transactions.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取交易记录失败')
    }
  } catch (error) {
    console.error('加载交易记录失败:', error)
    ElMessage.error('加载交易记录失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  loadTransactions()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadTransactions()
}

// 处理充值
const handleDeposit = async () => {
  if (!depositFormRef.value) return
  
  await depositFormRef.value.validate(async (valid) => {
    if (valid) {
      depositLoading.value = true
      try {
        // 调用API接口
        const response = await depositTokens(depositForm.amount)
        if (response.code === 200) {
          // 更新本地代币余额
          const result = userStore.depositTokens(depositForm.amount)
          if (result) {
            ElMessage.success('充值成功')
            depositDialogVisible.value = false
            loadTransactions() // 刷新交易记录
          }
        } else {
          ElMessage.error(response.message || '充值失败')
        }
      } catch (error) {
        console.error('充值失败:', error)
        ElMessage.error('充值失败: ' + (error.message || '未知错误'))
      } finally {
        depositLoading.value = false
      }
    }
  })
}

// 处理提现前检查
const handleWithdraw = () => {
  if (tokenBalance.value <= 0) {
    ElMessage.warning('您的代币余额为0，无法进行提现操作')
    return
  }
  
  withdrawForm.amount = Math.min(100, tokenBalance.value)
  withdrawDialogVisible.value = true
}

// 确认提现
const confirmWithdraw = async () => {
  if (!withdrawFormRef.value) return
  
  await withdrawFormRef.value.validate(async (valid) => {
    if (valid) {
      withdrawLoading.value = true
      try {
        // 自动获取用户的银行账户信息
        const bankInfo = {
          name: isCompany.value ? '企业银行账户' : '个人银行账户',
          account: '系统自动关联的银行账户'
        }
        
        // 调用API接口
        const response = await withdrawTokens(withdrawForm.amount, bankInfo)
        if (response.code === 200) {
          // 更新本地代币余额
          const result = userStore.withdrawTokens(withdrawForm.amount)
          if (result) {
            ElMessage.success(response.message || '提现申请提交成功')
            withdrawDialogVisible.value = false
            loadTransactions() // 刷新交易记录
          }
        } else {
          ElMessage.error(response.message || '提现失败')
        }
      } catch (error) {
        console.error('提现失败:', error)
        ElMessage.error('提现失败: ' + (error.message || '未知错误'))
      } finally {
        withdrawLoading.value = false
      }
    }
  })
}

// 查看交易详情
const viewTransaction = (transaction) => {
  selectedTransaction.value = transaction
  transactionDetailVisible.value = true
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态样式类型
const getStatusType = (status) => {
  switch (status) {
    case 'completed': return 'success'
    case 'processing': return 'warning'
    case 'failed': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'completed': return '已完成'
    case 'processing': return '处理中'
    case 'failed': return '失败'
    default: return '未知状态'
  }
}
</script>

<style scoped>
.wallet-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #333;
}

.balance-card,
.transaction-card {
  margin-bottom: 20px;
}

.balance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.balance-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.balance-actions {
  display: flex;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item,
.detail-item {
  margin-bottom: 10px;
  display: flex;
}

.label {
  width: 120px;
  color: #909399;
}

.value {
  flex: 1;
  color: #303133;
}

.transaction-detail {
  padding: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .info-item,
  .detail-item {
    flex-direction: column;
  }
  
  .label {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style> 